/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ejb.otherUtil;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.MenuModel;

/**
 *
 * @author Vick
 */
@ManagedBean
public class MenubarManagedBean
{

    private MenuModel menubar = new DefaultMenuModel();

    public MenubarManagedBean()
    {
	// Create menu items required
	DefaultMenuItem home = new DefaultMenuItem("Home");
	DefaultMenuItem signUp = new DefaultMenuItem("Sign up");
	DefaultMenuItem logIn = new DefaultMenuItem("Log in");
	DefaultMenuItem logOut = new DefaultMenuItem("Log out");

	// Create menuitems required
	home.setUrl("/");
	//TODO: add action for sign up
	signUp.setCommand("#{menubarManagedBean.ajaxAction}");
	signUp.setAjax(false);
	logIn.setUrl("/faces/login.xhtml");
	logIn.setAjax(false);
	logOut.setCommand("#{logoutBean.logout()}");
	logOut.setAjax(false);

	// Associate submenus with the menubar
	this.menubar.addElement(home);

	//Check if the user has logged in
	FacesContext context = FacesContext.getCurrentInstance();
	HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

	if (request.isUserInRole("admin") || request.isUserInRole("user"))
	{
	    DefaultMenuItem userName = new DefaultMenuItem(request.getUserPrincipal().getName());
	    this.menubar.addElement(userName);
	    //TODO: add link to personal profile
	    this.menubar.addElement(logOut);
	} else
	{
	    this.menubar.addElement(signUp);
	    this.menubar.addElement(logIn);
	}
    }

    public MenuModel getMenubar()
    {
	return menubar;
    }

    public void setMenubar(MenuModel menubar)
    {
	this.menubar = menubar;
    }

    public String ajaxAction()
    {
	FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
	return "";
    }

    public String nonAjaxAction()
    {
	return "";
    }
}
